#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char shellcode[] = {
  0x31, 0xc0, 0x50, 0x68, 0x2e, 0x2e, 0x2e, 0x20, 0x68, 0x74, 0x69, 0x6f,
  0x6e, 0x68, 0x71, 0x75, 0x65, 0x73, 0x68, 0x73, 0x20, 0x61, 0x20, 0x68,
  0x68, 0x61, 0x74, 0x27, 0x68, 0x6c, 0x2c, 0x20, 0x74, 0x68, 0x73, 0x68,
  0x65, 0x6c, 0x68, 0x20, 0x74, 0x6f, 0x20, 0x68, 0x20, 0x6e, 0x6f, 0x74,
  0x68, 0x2c, 0x20, 0x6f, 0x72, 0x68, 0x68, 0x65, 0x6c, 0x6c, 0x68, 0x54,
  0x6f, 0x20, 0x73, 0x89, 0xe1, 0x31, 0xdb, 0x43, 0xba, 0x30, 0x00, 0x00,
  0x00, 0xb0, 0x04, 0xcd, 0x80, 0xb0, 0x03, 0x31, 0xdb, 0xba, 0x01, 0x00,
  0x00, 0x00, 0xcd, 0x80, 0x53, 0x68, 0x6c, 0x3a, 0x70, 0x0a, 0x68, 0x73,
  0x68, 0x65, 0x6c, 0x68, 0x74, 0x68, 0x65, 0x20, 0x68, 0x67, 0x65, 0x74,
  0x20, 0x68, 0x6e, 0x27, 0x74, 0x20, 0x68, 0x75, 0x20, 0x63, 0x61, 0x68,
  0x2c, 0x20, 0x79, 0x6f, 0x68, 0x64, 0x69, 0x6e, 0x67, 0x68, 0x20, 0x6b,
  0x69, 0x64, 0x68, 0x4a, 0x75, 0x73, 0x74, 0x89, 0xe1, 0x43, 0xba, 0x28,
  0x00, 0x00, 0x00, 0xb0, 0x04, 0xcd, 0x80, 0xb0, 0x01, 0x31, 0xdb, 0xcd,
  0x80
};

typedef int (*FUNC)();

void neverget() {
    system("/bin/sh");
}

void check(char *buf) {
    FILE *infile = fopen("/home/ctf/key.txt", "r");
    char input[40], answer[40];
    FUNC ptr = shellcode;
    fread(answer, 1, 39, infile);
    fclose(infile);
    strncpy(input, buf, strlen(buf));
    if(strcmp(input, answer) == 0) {
        neverget();
    }
    else {
        ptr();
    }
}

void read_passphrase(char *buf) {
    char chr;
    unsigned int idx = 0;
    int ret;
    while(idx <= 39) {
        ret = read(0, &chr, 1);
        if(ret >= 0) {
            if(!ret || chr == '\n') {
                buf[idx] = '\0';
                break;
            }
            buf[idx++] = chr;
        }
        else {
            buf[idx] = '\0';
            break;
        }
    }
}

int main() {
    unsigned int id = 0;
    char buf[40];
    setvbuf(stdout, 0LL, 2, 0LL);
    setvbuf(stdin, 0LL, 1, 0LL);
    memset(buf, '\0', 40);
    printf("What's your secure id?\n");
    scanf("%d", &id);
    printf("Give me a passphrase to get the shell!!!\n");
    read_passphrase(buf);
    check(buf);
}
